//导入axios  npm install axios
import axios from 'axios';
import {ElMessage} from 'element-plus'
import {userStore} from '../stores/user.js'
//定义一个变量,记录公共的前缀  ,  baseURL
const baseURL = 'http://localhost:8080';
const instance = axios.create({baseURL})

//添加请求拦截器，发送请求配置token
instance.interceptors.request.use(
    (config) => {
        //请求前的回调,添加token
        const tokenStore = userStore();
        //判断有没有token,当token不为空，则tokenStore.token为true
        if (tokenStore.token) {
            config.headers['satoken'] = tokenStore.token
        }
        return config;
    },
    (err) => {
        //请求错误的回调
        Promise.reject(err)
    }
)
//返回结果之后
instance.interceptors.response.use(
    response => {
        let res = response.data;
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }
        return res
    },
    err => {
        if (err.response.status === 404) {
            ElMessage.error('未找到请求接口')
        } else {
            ElMessage.error('服务异常')
        }
        return Promise.reject(err);//异步的状态转化成失败的状态
    }
)

export default instance;